<template>
  <div style="background-color: #FFFFFF;padding: 15px">
    <span style="font-size: 19px;font-weight: 600">用户列表</span><br><br><br>

    <a-form layout='inline' :model="myInformation">
      <a-form-item name="userAccount">
        <div class="course-name">账号名称：</div>
        <a-input :style="{ width: '200px' }" placeholder="请输入账号名称" v-model:value="myInformation.userAccount"/>
      </a-form-item>
      <a-form-item name="userName">
        <div class="course-name">用户姓名：</div>
        <a-input :style="{ width: '200px' }" placeholder="请输入用户姓名" v-model:value="myInformation.userName"/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="searchByInput" style="margin-left:15px">
          <search-outlined />
          查询
        </a-button>
        <a-button @click="refresh" style="margin-left:15px">
          <redo-outlined />
          重置
        </a-button>

        <a-button type="primary" @click="addUser" style="margin-left:15px">
          <plus-circle-outlined />
          新增用户
        </a-button>
      </a-form-item>
    </a-form>
    <div style="height: 20px;"></div>
  </div>

  <div class="workContent">
    <a-spin :spinning="mySpinning">
      <a-table :columns="columns" :data-source="userList" bordered :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex == 'userAvatar'">
            <a-image :preview="false" style="width: 30px;height: 30px;border-radius: 50%" :src="text"></a-image>
          </template>

          <template  v-if="column.dataIndex === 'operation'">
            <a style="margin-right: 10px" @click="editUser(record)">编辑</a><a-divider type="vertical" />
            <a-popconfirm
                v-if="userList.length"
                title="确认删除吗?"
                cancelText="取消"
                okText="确认"
                @confirm="onDelete(record.id)"
            >
              <template #icon><question-circle-outlined style="color: red" /></template>
              <a style="color: red;margin-left: 10px">删除</a>
            </a-popconfirm>
          </template>
        </template>
      </a-table>

      <div style="width: 100%;height: 55px;">
        <a-pagination style="float: right;margin-top: 10px" v-model:current="current"
                      @change="changeNum"
                      :total="total" show-less-items />
      </div>

    </a-spin>

    <a-modal v-model:visible="visible" title="新增用户"
             :footer="null" @cancel="resetFields">
      <a-form
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="upload" label="上传头像" >
          <div style="margin-top: -5px">
            <input class="input_image left" id="file" type="file" @change="change" accept="image/*" />
            <img class="show_input_image left" v-if="addAUser.userAvatar != ''" :src="addAUser.userAvatar" />
            <img class="show_input_image left" v-if="addAUser.userAvatar ==''" src="/img/addAva.png" />
          </div>
        </a-form-item>

        <a-form-item
            label="账号名称" v-bind="validateInfos.userAccount"
        >
          <a-input v-model:value="addAUser.userAccount" />
        </a-form-item>

        <a-form-item
            label="用户姓名"
            v-bind="validateInfos.userName"
        >
          <a-input v-model:value="addAUser.userName" />
        </a-form-item>

        <a-form-item
            label="账号密码"
            v-bind="validateInfos.userPassword"
        >
          <a-input-password v-model:value="addAUser.userPassword" />
        </a-form-item>

        <a-form-item
            label="用户性别"
            name="gender"
            v-bind="validateInfos.gender"
        >
          <a-radio-group v-model:value="addAUser.gender">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="0">女</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
            label="电话号码"
            v-bind="validateInfos.phone"
        >
          <a-input v-model:value="addAUser.phone" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
          <a-button type="dashed" @click="resetFields">重置</a-button>&nbsp;&nbsp;&nbsp;&nbsp;
          <a-button type="primary" @click.prevent="handleOk">确认</a-button>
        </a-form-item>

      </a-form>
    </a-modal>
  </div>

</template>

<script>
import {reactive, toRefs} from "vue";
import {addUserFunction, deleteUser, getUserList, updateUserInfo} from "@/utils/user";
import {message, notification} from "ant-design-vue";
import {PlusCircleOutlined, RedoOutlined, SearchOutlined, QuestionCircleOutlined ,PlusOutlined, LoadingOutlined} from "@ant-design/icons-vue";
import axios from "axios";
import { Form } from 'ant-design-vue';
const useForm = Form.useForm;

export default {
  components: {
    SearchOutlined,
    RedoOutlined,
    PlusCircleOutlined,
    PlusOutlined, LoadingOutlined,QuestionCircleOutlined
},

  setup(){
    const state = reactive({
      myInformation: {
        userName: '',
        userAccount: '',
      },
      userList: [],
      mySpinning: undefined,
      total: undefined,
      current: 1,
      visible: false,
      addAUser: {
        gender: undefined,
        userAccount: "",
        userAvatar: "",
        userName: "",
        userPassword: "",
        userRole: "",
        phone: '',
        id: undefined,
      },
      fileList: [],      //上传文件列表
      loading: false,        //上传文件loding
      isEdit: undefined,     //是否为编辑
      newEdit: {},         //正在编辑的用户信息
    })

    const columns = [
      {
        title: '用户头像',
        dataIndex: 'userAvatar',
        key: 'userAvatar'
      },
      {
        title: '用户id',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '账号名称',
        dataIndex: 'userAccount',
        key: 'userAccount',
      },
      {
        title: '用户姓名',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '性别',
        dataIndex: 'gender',
        key: 'gender',
      },
      {
        title: '电话号码',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
      },
      {
        title: '操作',
        dataIndex: 'operation',
      }
    ]

    const getUserListByApi = function (name,account,num){
      state.mySpinning = true
      getUserList(name,account,num).then(res => {
        if (res.data.code === 0){
          state.mySpinning = false
          state.userList = res.data.data.records
          state.total = res.data.data.total
          state.userList.forEach(e => {
            if (e.gender == 1){
              e.gender = '男'
            }else{
              e.gender = '女'
            }
            e.updateTime = formatDate(e.updateTime)
          })
        }else{
          message.error('获取失败，请刷新后重试')
        }
      })
    }

    getUserListByApi(state.myInformation.userName,state.myInformation.userAccount,1)

    //搜索按钮
    const searchByInput = function (){
      getUserListByApi(state.myInformation.userName,state.myInformation.userAccount,1)
    }

    //重置搜索
    const refresh = function (){
      state.myInformation.userName = ''
      state.myInformation.userAccount = ''
      getUserListByApi(state.myInformation.userName,state.myInformation.userAccount,1)
    }

    //删除用户
    const onDelete = id => {
      let deleteRequest = {
        id: id,
      }
      deleteUser(deleteRequest).then(res => {
        if(res.data.code === 0){
          message.success('删除成功')
          getUserListByApi('','',1)
        }else{
          message.error('删除失败')
        }
      })
    };

    //分页换页
    const changeNum = function (page){
      getUserListByApi(state.myInformation.userName,state.myInformation.userAccount,page)
    }

    function formatDate(time){
      let nyr = time.slice(0, 10)
      let sfm = time.slice(11,19)

      let newTime = nyr + ' ' + sfm

      return newTime;
    }


    const rulesRef = reactive({
      userAccount: [{
        required: true,
        message: '请输入账户名称',
      }],
      userName: [{
        required: true,
        message: '请输入用户姓名',
      }],
      userPassword: [{
        required: true,
        message: '请输入密码',
      }],


    });

    //点击增加用户按钮
    const addUser = function (){
      state.isEdit = false
      state.visible = true
    }

    //点击编辑按钮
    const editUser = function (item){
      state.addAUser.userPassword = item.userPassword
      state.addAUser.userName = item.userName
      state.addAUser.phone = item.phone
      state.addAUser.userAvatar = item.userAvatar
      if (item.gender == '男')
        state.addAUser.gender = 1
      if (item.gender == '女')
        state.addAUser.gender = 0
      state.addAUser.userAccount = item.userAccount
      state.addAUser.id = item.id
      state.isEdit = true
      state.visible = true
      state.newEdit = item
    }

    //新增用户模态框确认
    const handleOk = function (){
      validate().then(() => {
        if (state.isEdit == false){
          let userAddRequest = {
            gender: state.addAUser.gender,
            phone: state.addAUser.phone,
            userAccount: state.addAUser.userAccount,
            userAvatar: state.addAUser.userAvatar,
            userName: state.addAUser.userName,
            userPassword: state.addAUser.userPassword
          }
          addUserFunction(userAddRequest).then(res => {
            if (res.data.code === 0){
              message.success('增加用户成功')
              getUserListByApi('','',1)
            }else{
              message.error('增加用户失败')
            }
          })
          state.visible = false
          resetFields()
        }else if (state.isEdit == true){
          let userUpdateRequest = {
            gender: state.addAUser.gender,
            id: state.addAUser.id,
            phone: state.addAUser.phone,
            userAccount: state.addAUser.userAccount,
            userAvatar: state.addAUser.userAvatar,
            userName: state.addAUser.userName,
            userPassword: state.addAUser.userPassword,
          }
          updateUserInfo(userUpdateRequest).then(res=>{
            if (res.data.code === 0){
              message.success('编辑成功')
              getUserListByApi('','',1)
            }else{
              message.error('编辑失败')
            }
          })
          state.visible = false
          resetFields()
        }

      }).catch(err => {
        console.log('error', err);
      });
    }

    const {
      resetFields,
      validate,
      validateInfos,
    } = useForm(state.addAUser, rulesRef, {
      onValidate: (...args) => console.log(),
    });

    const change = function (e){
      let imgInput = document.getElementById('file')

      if (!imgInput.value){
        message.error('没有选择图片')
      }

      let file = imgInput.files[0];
      let size = file.size;
      if (size >= 1 * 1024 * 1024) {
        message.error('文件大小超出限制')
        return false;
      }
      if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
        message.error('不是有效的图片')
        return;
      }
      let formData = new FormData()
      formData.append('file',file)

      axios.post('http://121.37.0.16:8080/api/file/upload',formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code == 0){
          state.addAUser.userAvatar = 'http://121.37.0.16:9000/public/'+ res.data.data.fileName[0]
        }
      })
    }


    return{
      ...toRefs(state),
      searchByInput,
      refresh,
      changeNum,
      change,
      addUser,
      handleOk,
      onDelete,
      editUser,
      columns,
      resetFields,
      validateInfos,
    }
  }
}
</script>

<style scoped>
.course-name {
  width: 100px;
  margin-left: -2px;
  text-align: center;
  line-height: 32px;
  display: inline-block;
}

.workContent{
  width: 96%;margin: 25px auto 0 auto;
}

.show_input_image {
  margin-top: -60px;
  width: 60px;
  height: 60px;
  border: 1px solid #f0f0f0;
}
.input_image {
  position: relative;
  width: 60px;
  height: 60px;
  background-color: blue;
  z-index: 999;
  opacity: 0;
  border-radius: 50%;
}
</style>

<style>
.ant-modal-title{
  font-weight: 600;
}
</style>